package com.ygqh.baby.controller.open;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.ResponseEntity;
import com.ygqh.baby.model.StockVo;
import com.ygqh.baby.po.YgStock;
import com.ygqh.baby.service.YgStockService;
@CrossOrigin
@RequestMapping("/open/stock")
@RestController
public class StockController extends KidsBaseController{
	private Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());

	@Autowired
	private YgStockService ygStockService;

	@RequestMapping("/findStockBySkuCodes")
	@ResponseBody
	public ResponseEntity findStockBySkuCodes(@RequestParam String... skuCodes){
		List<StockVo> list = ygStockService.findStockVoBySkuCodes(skuCodes);
		return ResponseEntity.success(list);
		
	}
	@RequestMapping("/findStockByProductCodes")
	@ResponseBody
	public ResponseEntity findByProductCodes(@RequestParam String... productCodes){
		List<StockVo> list = ygStockService.findStockVoByProductCodes(productCodes);
		return ResponseEntity.success(list);
		
	}
	
	/**
	 * 基于skuCode 更新
	* @Title: findByProductCodes 
	*  @param stocks
	*  @param from
	*  @return    入参
	* @return ResponseEntity    返回类型
	* @author （guohao） 
	* @throws
	* @date 2018年11月26日 下午4:50:07 
	* @version V1.0
	 * @return 
	 */
	@RequestMapping("/reduceStock")
	@ResponseBody
	public ResponseEntity reduceStock(HttpServletRequest request){
		int reduceStock;
		try {
			ResponseEntity validToken = validToken(request);
			if(!validToken.isSuccess()){
				return validToken;
			}
			String requestPostStr = getRequestPostStr(request);
			logger.info("收到新世界推送库存信息。【{}】", requestPostStr);
			if (StringUtil.isBlank(requestPostStr)) {
				return ResponseEntity.success();
			}
			List<YgStock> stocks = JSONObject.parseObject(requestPostStr, new TypeReference<List<YgStock>>() {
			});
			for (YgStock stock : stocks) {
				if(StringUtil.isBlank(stock.getSkuCode()) || stock.getAmount() == null){
					return ResponseEntity.error("skucode/amount 存在 null/空 值");
				}
				stock.setRealAmount(stock.getAmount());
			}
			reduceStock = ygStockService.reduceStock(stocks, "Kids");
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.error("未知错误。",e.getMessage());
		}
		return ResponseEntity.success(reduceStock);
		
	}
}
